﻿using System;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace PTCScheduler
{
/// <summary>
/// Class to handle the exporting of desired datagrid to Excel/.CSV file.
/// </summary>
 
    public class CSVExport
    {
        //Variable to hold instance of excel application.
        private Microsoft.Office.Interop.Excel.Application xlexcel;

        //Variable to hold instance of excel workbook.
        private Microsoft.Office.Interop.Excel.Workbook xlWorkBook;

        //Variable to hold instance of excel worksheet.
        private Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

        //Variable to hold missing value.
        private Object missValue = System.Reflection.Missing.Value;

        //Variable to hold excel pasting range.
        private Microsoft.Office.Interop.Excel.Range chartRange;

        //Constructor that takes in datagrid to be exported.
        public CSVExport(System.Windows.Controls.DataGrid dataGrid)
        {
            //Export the data when new CSVExport instance is created.
            export(dataGrid);
        }

        //Method to export datagrid to excel application.
        public void export(System.Windows.Controls.DataGrid dataGrid)
        {
            try
            {
                //Select all cells in datagrid and copy to clipboard.
                dataGrid.SelectAllCells();
                dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; //Includes DataGrid Column Headers.
                ApplicationCommands.Copy.Execute(null, dataGrid);

                //Clear the clipboard.
                dataGrid.UnselectAllCells();

                //Create instance of the excel application and make it visible.
                xlexcel = new Microsoft.Office.Interop.Excel.Application();
                xlexcel.Visible = true;

                //Add a new workbook to the excel instance.
                xlWorkBook = xlexcel.Workbooks.Add(missValue);

                //Set the default sheet as the sheet to work with.
                xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                //Set the range of the cells. 
                chartRange = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
                chartRange.Select();

                //Paste data to the excel worksheet.
                xlWorkSheet.Paste(chartRange, false);

                //Clear data from clipboard.
                Clipboard.Clear();
            }
            catch (NotSupportedException)
            {
                //Tell user no data
                MessageBox.Show("Excel is not supported on this computer.");
            }
        }
    }
}
